var util = require('util');
var ElasticSearchClient = require('elasticsearchclient');
var JsonReader = require(__dirname + '/../util/jsonReader');
var config = JsonReader.read(__dirname
		+ '/../../config/search/searchConfig.json');

var serverOptions = {
	host : config.elServerHost,
	port : config.elServerPort
};

function getRandomNumber(min, max) {
	return Math.floor((Math.random() * max) + min);
}

var chars = 'abcdefghigjlmnopq rstuvwxyz';
var noSpaceChars = 'abcdefghigjlmnopqrstuvwxyz';

function getRandomString() {
	var size = getRandomNumber(3, 10);
	var result = [];
	for (var i = 0; i < size; i++) {
		var charIndex = getRandomNumber(0, chars.length - 1);
		result.push(chars[charIndex]);
	}
	return result.join('');
}

function getNoSpaceRandomString() {
	var size = getRandomNumber(3, 10);
	var result = [];
	for (var i = 0; i < size; i++) {
		var charIndex = getRandomNumber(0, noSpaceChars.length - 1);
		result.push(noSpaceChars[charIndex]);
	}
	return result.join('');
}

//console.time('Init 100m documents');
var batchCount = 10;
var batchSize = 100;
for (var i = 0; i < batchCount; i++) {
	var searchClient = new ElasticSearchClient(serverOptions);
	var bulkCommands = [];
	for (var j = 0; j < batchSize; j++) {
		var document = {
			"id" : i * batchSize + j,
			"accountId" : "123",
			"username" : getRandomString(),
			"emailAddress" : getNoSpaceRandomString() + '@'
					+ getNoSpaceRandomString() + '.com',
			"firstName" : getRandomString(),
			"lastName" : getRandomString(),
			"realms" : {
				"SpendManagement" : {
					"id" : "111",
					"accountId" : "SM accountId",
					"businessEmailAddress" : "XXX"
				},
				"Conference" : {
					"id" : "Conference userId",
					"accountId" : "Conference accountId",
					"lastUpdatedBy" : "Conference userId",
					"createdBy" : "Conference userId"
				}
			}
		};
		bulkCommands.push({
			"index" : {
				"_index" : "cloud_index_v1",
				"_type" : "user",
				"_id" : document['id']
			}
		});
		bulkCommands.push(document);
	}

	console.log('Index %d to %d', i * 10, (i + 1) * 10);
	searchClient.bulk(bulkCommands, null, function(error, result) {
		if (error) {
			throw error;
		}
		console.log('Index finished');
	});
}
